package com.webservice.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.webservice.dao.IAllotInBillBackDao;
import com.webservice.vo.AllotInBillDetailInfo;
import com.webservice.vo.AllotInBillImeiInfo;

@Repository("AllotInBillBackDao")
public class AllotInBillBackDaoImpl implements IAllotInBillBackDao {

	@Autowired
	@Qualifier("datatemplate")
	private JdbcTemplate jdbcTemplate;

	@Override
	public int updateInBill(String outcode, String state) {
		// TODO Auto-generated method stub
		String sql = "UPDATE BI_INTOSTORE SET ALLOTSTATE=" + state
				+ " WHERE INTOBILL='" + outcode + "' AND DR=0";
		System.out.println("更新入库单状态:" + sql);
		int i = this.jdbcTemplate.update(sql);
		return i;
	}

	@Override
	public int updateAllotBill(String allotcode) {
		// TODO Auto-generated method stub
		String sql = "UPDATE bi_allot SET allotstatus=5 WHERE allotcode=? AND DR=0";
		System.out.println("更新调拨单状态为调拨完成:" + sql);
		int i = this.jdbcTemplate.update(sql, new Object[] { allotcode });
		return i;
	}

	@Override
	public int[] batchInsertInBillDetail(List<AllotInBillDetailInfo> details) {
		// TODO Auto-generated method stub
		String sql = "INSERT INTO BI_INTODETAIL(PK_INTODETAIL,BILLCODE,QUANTITY,PRODUCTID,DR,TS,SUPPLYID,ACTUALNUM,TYPE) VALUES(?,?,?,?,?,?,?,?,?)";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for (AllotInBillDetailInfo detail : details) {
			Object[] args = new Object[9];
			args[0] = detail.getPk_intodetail();
			args[1] = detail.getBillcode();
			args[2] = detail.getQuantity();
			args[3] = detail.getProducid();
			args[4] = detail.getDr();
			args[5] = detail.getTs();
			args[6] = detail.getSupplyid();
			args[7] = detail.getActualnum();
			args[8] = detail.getType();
			batchArgs.add(args);
		}
		int[] count = jdbcTemplate.batchUpdate(sql, batchArgs);
		return count;
	}

	/**
	 * 更新非定向发布数
	 * 
	 * @param intoStore
	 * @param details
	 * @return
	 */
	public int[] batchUpdateSupplyArea0(String intoStore,
			List<AllotInBillDetailInfo> details) {
		// TODO Auto-generated method stub
		String sql = "UPDATE SUPPLY_AREA0 T SET T.OVERPLUSNUMBER=NVL(T.OVERPLUSNUMBER,0)+?"
				+ " WHERE T.AREAID IN (SELECT AREAID  FROM AREAINFO  WHERE PARENTID IN (SELECT AREAID FROM RELATION_AREASTORAGE WHERE PK_STORDOC = ? AND AREAID!=2)" +
				" OR AREAID IN (SELECT AREAID FROM RELATION_AREASTORAGE WHERE PK_STORDOC = ? AND AREAID!=2))"
				+ " AND T.SUPPLYPRODUCTID IN(SELECT ID FROM SHOP_PRODUCT WHERE PRODUCTID=? AND SUPPLYID=? AND SALEMODE='02' AND DEL_FLAG='1') AND SALETYPE = '2' AND DEL_FLAG = '1'";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for (AllotInBillDetailInfo detail : details) {
			Object[] args = new Object[5];
			args[0] = detail.getActualnum();
			args[1] = intoStore;
			args[2] = intoStore;
			args[3] = detail.getProducid();
			args[4] = detail.getSupplyid();
			if ("1".equals(detail.getType())) {
				batchArgs.add(args);
			}
		}
		if (batchArgs.size() > 0) {
			jdbcTemplate.batchUpdate(sql, batchArgs);
		}
		return new int[1];
	}

	@Override
	public int[] batchInsertInBillImei(List<AllotInBillImeiInfo> details) {
		// TODO Auto-generated method stub
		String sql = "INSERT INTO BI_INTOIMEI(PK_INTOIMEI,PK_INTODETAIL,IMEI,DR,TS,IMEITYPE) VALUES(?,?,?,?,?,?)";
		List<Object[]> batchArgs = new ArrayList<Object[]>();
		for (AllotInBillImeiInfo detail : details) {
			Object[] args = new Object[6];
			args[0] = detail.getPk_intoimei();
			args[1] = detail.getPk_intobilldetail();
			args[2] = detail.getImei();
			args[3] = detail.getDr();
			args[4] = detail.getTs();
			args[5] = detail.getImeitype();
			batchArgs.add(args);
		}
		int[] count = jdbcTemplate.batchUpdate(sql, batchArgs);
		return count;
	}

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public int getQuantity(String allotcode, String productcode, String supplyid) {
		// TODO Auto-generated method stub
		int quantity = 0;
		String sql = "SELECT NVL(QUANTITY,0) AS QUANTITY FROM BI_ALLOTDETAIL WHERE ALLOTCODE=? AND SUPPLYID=? AND PRODUCTID=? AND DR=0 AND ROWNUM=1";
		Object[] parms = { allotcode, supplyid, productcode };

		List<String> li = (List<String>) jdbcTemplate.query(sql, parms,
				new RowMapper<String>() {
					public String mapRow(ResultSet rs, int i)
							throws SQLException {
						String vo = rs.getString(1);
						return vo;
					}
				});
		if (li != null && li.size() > 0) {
			String q = li.get(0);
			if ("".equals(q)) {
				quantity = 0;
			} else {
				quantity = Integer.parseInt(q);
			}
		} else {
			quantity = 0;
		}
		// quantity=this.jdbcTemplate.queryForInt(sql,parms);
		return quantity;
	}

	@Override
	public int updateFromStoreNum(String fromstore,
			List<AllotInBillDetailInfo> details) {
		int counts = 0;
		for (AllotInBillDetailInfo detail : details) {
			if ("1".equals(detail.getType())) {
				counts++;
			}
		}
		if (counts > 0) {
			String[] sqls = new String[counts];
			int count = 0;
			for (AllotInBillDetailInfo detail : details) {
				if ("1".equals(detail.getType())) {
					String sql = "UPDATE STORE_PRODUCT SET ONWAYNUMBER=NVL(ONWAYNUMBER,0)-"
							+ detail.getQuantity()
							+ " WHERE PK_STORDOC='"
							+ fromstore
							+ "' AND PRODUCTID='"
							+ detail.getProducid()
							+ "' AND SUPPLYID="
							+ detail.getSupplyid();
					sqls[count++] = sql;
				}
			}
			jdbcTemplate.batchUpdate(sqls);
		}
		return counts;
	}

	@Override
	public int updateToStoreNum(String tostore,
			List<AllotInBillDetailInfo> details) {
		int counts = 0;
		for (AllotInBillDetailInfo detail : details) {
			if ("1".equals(detail.getType())) {
				counts++;
			}
		}
		if (counts > 0) {
			String[] sqls = new String[counts];
			int count = 0;
			for (AllotInBillDetailInfo detail : details) {
				if ("1".equals(detail.getType())) {
					String qSql = "SELECT PK_STORDOC FROM STORE_PRODUCT WHERE PK_STORDOC='"
							+ tostore
							+ "' AND PRODUCTID="
							+ detail.getProducid()
							+ " AND SUPPLYID="
							+ detail.getSupplyid();
					List<String> qList = this.jdbcTemplate.query(qSql,
							new RowMapper<String>() {
								@Override
								public String mapRow(ResultSet rs, int i)
										throws SQLException {
									return rs.getString(1);
								}
							});
					String sql = "";
					if (qList != null && qList.size() > 0) {
						sql = "UPDATE STORE_PRODUCT SET ALLOCATABLE=NVL(ALLOCATABLE,0)+"
								+ detail.getActualnum()
								+ " WHERE PK_STORDOC='"
								+ tostore
								+ "' AND PRODUCTID='"
								+ detail.getProducid()
								+ "' AND SUPPLYID="
								+ detail.getSupplyid();
					} else {
						sql += "INSERT INTO STORE_PRODUCT(ID,PK_STORDOC,PRODUCTID,QUANTITY,ALLOCATABLE,SUPPLYID) values( SEQ_STORE_PRODUCT.nextval,'";
						sql += tostore;
						sql += "',";
						sql += detail.getProducid();
						sql += ",";
						sql += detail.getActualnum();
						sql += ",";
						sql += detail.getActualnum();
						sql += ",";
						sql += detail.getSupplyid();
						sql += ")";
					}
					sqls[count++] = sql;
					String strsql = "insert into store_product_log (pk_stordoc,productid, allocatable,optype,optime,supplyid) values(?,?,?,'01',sysdate,?)";
					Object args [] = new Object[]{tostore,detail.getProducid(),detail.getActualnum(),detail.getSupplyid()};
					jdbcTemplate.update(strsql,args);
				}
			}
			jdbcTemplate.batchUpdate(sqls);
		}
		return counts;
	}

	@Override
	public List<String[]> getPkStore(String allotcode) {
		// TODO Auto-generated method stub
		String sql="SELECT T.PK_FROMSTORE,T.PK_TOSTORE FROM BI_ALLOT T WHERE T.ALLOTCODE=? AND DR=0 ";
		return this.jdbcTemplate.query(sql, new Object[]{allotcode}, new RowMapper<String[]>() {
			@Override
			public String[] mapRow(ResultSet rs, int i) throws SQLException {
				String[] s = new String[2];
				s[0]=rs.getString(1);
				s[1]=rs.getString(2);
				return s;
			}
		});
	}
	
	@Override
	public String getIntoStoreState(String allotcode) {
		// TODO Auto-generated method stub
		String sql="SELECT T.ALLOTSTATE FROM BI_INTOSTORE T WHERE  T.INTOBILL=? AND DR=0";
		List<String> list=this.jdbcTemplate.query(sql, new Object[]{allotcode}, new RowMapper<String>() {
			@Override
			public String mapRow(ResultSet rs, int i) throws SQLException {
				return rs.getString(1);
			}
		});
		
		if(list!=null&&list.size()>0){
			return list.get(0);
		}
		return "";
	}
	
	@Override
	public int updateAllotPlanStatus(String allotplanstatus, String relationallotcode)
	{
		StringBuffer sb=new StringBuffer();
		sb.append("UPDATE BI_ALLOTPLAN BAP SET BAP.ALLOTSTATUS = ? WHERE BAP.DR = 0 ");
		sb.append("AND EXISTS (SELECT 1 FROM BI_ALLOT BA WHERE BA.PK_ALLOT = BAP.PK_RELATIONALLOT AND BA.ALLOTCODE = ?)");
		
		Object[] para = new Object[] { allotplanstatus, relationallotcode };
		
		//更新计划单
		int n=jdbcTemplate.update(sb.toString(), para);
		
		return n;
	}

}
